package com.naiterui.ehp.bs.patient.utils.message;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.bo.patient.MsgMaPublishParamBO;
import com.naiterui.ehp.bp.constants.CommonConstant;
import com.naiterui.ehp.bp.domain.Patient;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.patient.constants.PatientJumperEnum;
import com.naiterui.ehp.bs.patient.exception.ExceptionCodes;
import com.naiterui.ehp.bs.patient.feign.RecomFeginClient;
import com.naiterui.ehp.bs.patient.service.IPatientService;
import com.naiterui.ehp.bs.patient.service.ISubscribeNoticeService;
import com.naiterui.ehp.bs.patient.service.ITemplateNoticeService;
import com.naiterui.ehp.bs.patient.service.message.IMessageSendService;
import com.naiterui.ehp.bs.wechat.config.WeChatConfig;
import com.naiterui.ehp.bs.wechat.service.ICustomMsgApiService;
import com.naiterui.ehp.bs.wechat.service.impl.WebAuthorizeApiServiceImpl;

import lombok.RequiredArgsConstructor;

/**
 * @author gaoliangliang
 * @date 2019-06-24 11:24
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class JavaWXMessage implements MessageTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(JavaWXMessage.class);

    private final ITemplateNoticeService templateNoticeService;
    private final IPatientService patientService;
    private final WeChatConfig weChatConfig;
    private final ICustomMsgApiService customMsgApiService;
    private final WebAuthorizeApiServiceImpl webAuthorizeApiServiceImpl;
    private final ISubscribeNoticeService subscribeNoticeService;
    private final RecomFeginClient recomFeginClient;
    private final IMessageSendService messageSendService;

    @Override
    public Integer send(String json, Integer templateId) {
        int status = ExceptionCodes.SUCCESS;
        JSONObject jsonObject = JSONObject.parseObject(json);
        Long patientId = jsonObject.getLong("patientId");
        Long doctorId = jsonObject.getLong("doctorId");
        Patient patient = patientService.getPatient(patientId);
        if (patient == null) {
            return status;
        }
        Integer errcode;
        switch (templateId) {
            case MessageConstant.TEMPLATEID_DRUGREMIND:
                // MedicationRemindSubscribe remindSubscribe =
                // MedicationRemindSubscribe.builder().drug(jsonObject.getString("drugName")).build();
                // remindSubscribe.setOpenId(patient.getOpenId());
                // remindSubscribe.setTargetPage(webAuthorizeApiServiceImpl.getWebAuthorizeUrlSilent(ConfigUtil.getString("wechat.redirect.common.url"),
                // PatientJumperEnum.DRUG_REMIND.encodeWxParamStr(jsonObject.getString("recomId"))));
                // LOGGER.info("用药提醒推送，params={}", json);
                // errcode = subscribeNoticeService.notice(remindSubscribe);
                // if (errcode != 0) {
                // DrugRemind drugRemind = new DrugRemind(
                // patient.getOpenId(),
                // jsonObject.getString("drugName"));
                // drugRemind.setTargetPage(webAuthorizeApiServiceImpl.getWebAuthorizeUrlSilent(ConfigUtil.getString("wechat.redirect.common.url"),
                // PatientJumperEnum.DRUG_REMIND.encodeWxParamStr(jsonObject.getString("recomId"))));
                // templateNoticeService.notice(drugRemind);
                // }
                this.messageSendService.publishMaMessage(MsgMaPublishParamBO.builder().doctorId(doctorId)
                    .patientId(patientId).msgType(MsgMaPublishParamBO.MsgType.MEDICATION_REMINDER)
                    .content(DateUtil.getCurrentCustomizeFormatDate("yyyy年MM月dd日 HHmm")).build());
                LOGGER.info("用药提醒推送结束");
                break;
            case MessageConstant.TEMPLATEID_REVISIT:
                // Revisit revisit = new Revisit(
                // patient.getOpenId(),
                // jsonObject.getString("doctorName"));
                // revisit.setOpenId(patient.getOpenId());
                // revisit.setTargetPage(webAuthorizeApiServiceImpl.getWebAuthorizeUrlSilent(ConfigUtil.getString("wechat.redirect.common.url"),
                // PatientJumperEnum.REVISIT_LIST.encodeWxParamStr(jsonObject.getString("doctorId"))));
                // LOGGER.info("随访提醒模板推送，params={}", json);
                // templateNoticeService.notice(revisit);
                LOGGER.info("随访提醒模板推送结束");
                break;
            case MessageConstant.TEMPLATEID_ALARMCLOCK:
                // Long recomId = jsonObject.getLong("recomId");
                // DrugRemindBO drugRemindBO = recomFeginClient.drugRemind(recomId);
                // Boolean valid = drugRemindBO.getValid();
                // PlanSubscribe planSubscribe = PlanSubscribe.builder().planName("用药计划").planStatus(valid ? "已开启" :
                // "未开启").build();
                // planSubscribe.setOpenId(patient.getOpenId());
                // planSubscribe.setTargetPage(webAuthorizeApiServiceImpl.getWebAuthorizeUrlSilent(ConfigUtil.getString("wechat.redirect.common.url"),
                // PatientJumperEnum.DRUG_REMIND.encodeWxParamStr(jsonObject.getString("recomId"))));
                // errcode = subscribeNoticeService.notice(planSubscribe);
                // LOGGER.info("用药闹钟模板推送，params={}", json);
                // if (errcode != 0) {
                // AlarmClock alarmClock = new AlarmClock(
                // patient.getOpenId(),
                // jsonObject.getString("doctorName"));
                // alarmClock.setTargetPage(webAuthorizeApiServiceImpl.getWebAuthorizeUrlSilent(ConfigUtil.getString("wechat.redirect.common.url"),
                // PatientJumperEnum.DRUG_REMIND.encodeWxParamStr(jsonObject.getString("recomId"))));
                // templateNoticeService.notice(alarmClock);
                // }
                this.messageSendService.publishMaMessage(MsgMaPublishParamBO.builder().doctorId(doctorId)
                    .patientId(patientId).msgType(MsgMaPublishParamBO.MsgType.MEDICATION_REMINDER)
                    .content(DateUtil.getCurrentCustomizeFormatDate("yyyy年MM月dd日 HHmm")).build());
                LOGGER.info("用药闹钟模板推送结束");
                break;
            case MessageConstant.TEMPLATEID_ALARMCLOCK_CONFIG:
                // LOGGER.info("用药闹钟保存客服消息推送，params={}", json);
                // customMsgApiService.sendSystemMsg(patient.getOpenId(),
                // jsonObject.getString("message"));
                LOGGER.info("用药闹钟保存客服消息推送结束");
                break;
            case MessageConstant.RECOMMEND_NOT_ORDER:
                LOGGER.info("推荐未购买提醒，params={}", json);
                // customMsgApiService.sendSystemMsg(patient.getOpenId(), jsonObject.getString("recomContent") +
                // "\n----------\n" +
                // webAuthorizeApiServiceImpl.getWebAuthorizeUrlSilent(ConfigUtil.getString("wechat.redirect.common.url"),
                // PatientJumperEnum.RECOM_DETAIL.encodeWxParamStr(jsonObject.getString("recomId")), "【查看处方】"));
                LOGGER.info("推荐未购买提醒结束");
                break;
            case MessageConstant.SESSION_FINISH:
                LOGGER.info("问诊结束提醒，params={}", json);
                // 是否添加医生详情链接
                Integer consultType = jsonObject.getInteger("consultType");
                Long consultSessionId = jsonObject.getLong("consultSessionId");
                // 结束回话，清除患者免责协议缓存
                RedisUtil.hashOps().hdel(CommonConstant.CONSULT_DISCLAIMER_ACTIVE, patientId + "_" + doctorId);

                String params = StringUtils.join(doctorId, "/", consultSessionId, "?type=", consultType);
                /*String complaintContent = webAuthorizeApiServiceImpl.getWebAuthorizeUrlSilent(ConfigUtil.getString("wechat.redirect.common.url"),
                        PatientJumperEnum.CONSULT_COMPLAINT.encodeWxParamStr(params), "【投诉】");*/
                String commentContent = webAuthorizeApiServiceImpl.getWebAuthorizeUrlSilent(
                    ConfigUtil.getString("wechat.redirect.common.url"),
                    PatientJumperEnum.CONSULT_COMMENT.encodeWxParamStr(params), "【满意度调查】");
                String content = StringUtils.join(jsonObject.getString("content"),
                    (doctorId == null ? "" : "\n----------\n"), "   ", commentContent);
                customMsgApiService.sendSystemMsg(patient.getOpenId(), content);
                LOGGER.info("问诊结束提醒结束");
                break;
            default:
                break;
        }
        return status;
    }
}
